<?php

namespace Admin\Controller;

class WithdrawController extends AdminbaseController {

    function _initialize() {
        parent::_initialize();
        $this->currentModel = D("Withdraw");
    }

    //首页
    public function index() {

        $requestMap = $this->convertRequestToMap();

        //分页
        $count = $this->currentModel->getListCount($requestMap);
        $page = $this->page($count, C("DEFAULT_PAGE_SIZE"));

        //获取withdraw列表
        $withdrawList = $this->currentModel->queryForList($page, $requestMap);

        $this->assign("typeEnum", C("WITHDRAW_TYPE"));
        $this->assign("statusEnum", C("WITHDRAW_STATUS"));
        $this->assign('withdrawList', $withdrawList);
        $this->assign("page", $page->show('Admin', $this->parameter));
        $this->display();

    }

    public function endWithdraw() {

        $id = $_REQUEST['id'];

        $withdraw = $this->currentModel->queryById($id);

        if($withdraw["status"] != C("WITHDRAW_STATUS.WAITING")) {
            $this->error("对不起,当前提现已过期,请重新再试");
        }

        $customer = D("Customer")->queryById($withdraw["customer_id"]);
        if($withdraw["money"] > $customer["frozen_assets"]) {
            $this->error("对不起,余额不够提现");
        }

        $arr = array(
            'mch_appid' => C('appid'),
            'mchid' => C('mch_id'),
            'nonce_str' => $this->createNoncestr(),
            'partner_trade_no' => time() . rand(0, 999),
            'openid' => $customer["openid"], //订单号
            'check_name' => 'NO_CHECK',
            'amount' => $withdraw["money"]*100,
            'desc' => '申请提现', //通知地址
            'spbill_create_ip' => get_client_ip(),
        );

        $arr['sign'] = $this->getSign($arr);  //签名

        $post = $this->curl_post_ssl('https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers', $this->arrayToXml($arr));

        $arr2 = $this->xmlToArray($post);

        if($arr2['return_code']=='SUCCESS'
            && $arr2['result_code'] == 'SUCCESS') {

            //修改状态
            $withdraw["status"] = C("WITHDRAW_STATUS.END");
            $this->currentModel->updateInfo($withdraw);

            //增加流水
            $accountDetailData["money"] = $withdraw["money"]*(-1);
            $accountDetailData["customer_id"] = $withdraw["customer_id"];
            $accountDetailData["create_time"] = getCurrentDate();
            $accountDetailData["type"] = C("ACCOUNT_DETAIL_TYPE.WITHDRAW");
            $accountDetailData["refer_id"] = $withdraw["withdraw_id"];
            D("AccountDetail")->add($accountDetailData);

            //减用户余额
            $customer["total_assets"]
                = $customer["total_assets"] - $withdraw["money"];
            $customer["frozen_assets"]
                = $customer["frozen_assets"] - $withdraw["money"];
            D("Customer")->updateInfo($customer);

        } else {

            $this->error("企业转账失败");

        }

        $this->success("处理成功", U("withdraw/index"));

    }

    function curl_post_ssl($url, $vars, $second=30,$aHeader=array()) {

        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

        //以下两种方式需选择一种

        //第一种方法，cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/cert-2/apiclient_cert.pem');
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'//cert-2/apiclient_key.pem');

        if( count($aHeader) >= 1 ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }

        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            return $data;
        }
        else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }


    /**
     * 	作用：生成签名
     */
    public function getSign($Obj) {

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;
    }

    /**
     * 	作用：array转xml
     */
    function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml.="<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml.="<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml.="</xml>";
        return $xml;
    }

    function signature() {
        $Obj['jsapi_ticket'] = jsapi_ticket();
        $Obj['noncestr'] = createNoncestr();
        $Obj['url'] = "http://" . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
        $Obj['timestamp'] = time();

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        //dump($Parameters);
        $String = formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        //$String = $String."&key=".C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = sha1($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        //$Obj['signature'] = strtoupper($String);
        $Obj['signature'] = $String;

        return $Obj;
    }

    /**
     * 	作用：产生随机字符串，不长于32位
     */
    public function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str.= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 	作用：格式化参数，签名过程需要使用
     */
    function formatBizQueryParaMap($paraMap, $urlencode) {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /**
     * 	作用：将xml转为array
     */
    public function xmlToArray($xml) {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

}